package com.hlf.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

public class AmountUtils {

    private static final Logger logger = LoggerFactory.getLogger(AmountUtils.class);

    /** 金额为分的格式 */
    public static final String CURRENCY_FEN_REGEX = "\\-?[0-9]+";

    /**
     * 将分为单位的转换为元并返回金额格式的字符串 （除100）
     * 
     * @param amount
     * @return
     * @throws Exception
     */
    public static String changeF2Y(Long amount) throws Exception {
        if (!amount.toString().matches(CURRENCY_FEN_REGEX)) {
            throw new Exception("金额格式有误");
        }

        int flag = 0;
        String amString = amount.toString();
        if (amString.charAt(0) == '-') {
            flag = 1;
            amString = amString.substring(1);
        }
        StringBuffer result = new StringBuffer();
        if (amString.length() == 1) {
            result.append("0.0").append(amString);
        } else if (amString.length() == 2) {
            result.append("0.").append(amString);
        } else {
            String intString = amString.substring(0, amString.length() - 2);
            for (int i = 1; i <= intString.length(); i++) {
                if ((i - 1) % 3 == 0 && i != 1) {
                    result.append(",");
                }
                result.append(intString.substring(intString.length() - i, intString.length() - i + 1));
            }
            result.reverse().append(".").append(amString.substring(amString.length() - 2));
        }
        if (flag == 1) {
            return "-" + result.toString();
        } else {
            return result.toString();
        }
    }

    /**
     * 将分为单位的转换为元 （除100）
     * 
     * @param amount
     * @return
     * @throws Exception
     */
    public static String changeF2Y(String amount) throws Exception {
        if (amount == null || "".equals(amount)) {
            return "0";
        }

        for (int i = 0; i < amount.length(); i++) {
            char[] aa = { '-' };
            aa[0] = amount.charAt(i);
            if (".".equals(new String(aa))) {
                amount = amount.substring(0, i);
            }
        }

        if (!amount.matches(CURRENCY_FEN_REGEX)) {
            throw new Exception("金额格式有误");
        }
        return BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).toString();
    }

    /**
     * 将元为单位的转换为分 （乘100）
     * 
     * @param amount
     * @return
     */
    public static String changeY2F(Long amount) {
        return BigDecimal.valueOf(amount).multiply(new BigDecimal(100)).toString();
    }

    /**
     * 将元为单位的转换为分 替换小数点，支持以逗号区分的金额
     * 
     * @param amount
     * @return
     */
    public static String changeY2F(String amount) {
        String currency = amount.replaceAll("\\$|\\￥|\\,", ""); // 处理包含, ￥
                                                                // 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0L;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }

    /**
     * 
     * 功能描述：去除字符串首部为"0"字符
     * 
     * @param str
     *            传入需要转换的字符串
     * @return 转换后的字符串
     */
    public static String removeZero(String str) {
        char ch;
        String result = "";
        if (str != null && str.trim().length() > 0 && !"null".equalsIgnoreCase(str.trim())) {
            try {
                for (int i = 0; i < str.length(); i++) {
                    ch = str.charAt(i);
                    if (ch != '0') {
                        result = str.substring(i);
                        break;
                    }
                }
            } catch (Exception e) {
                result = "";
            }
        } else {
            result = "";
        }
        return result;

    }

    public static String fenToYuan(Object o) {
        if (o == null) {
            return "0.00";
        }
        String s = o.toString();
        int len = -1;
        StringBuilder sb = new StringBuilder();
        if (s != null && s.trim().length() > 0 && !"null".equalsIgnoreCase(s)) {
            s = removeZero(s);
            if (s != null && s.trim().length() > 0 && !"null".equalsIgnoreCase(s)) {
                len = s.length();
                int tmp = s.indexOf("-");
                if (tmp >= 0) {
                    if (len == 2) {
                        sb.append("-0.0").append(s.substring(1));
                    } else if (len == 3) {
                        sb.append("-0.").append(s.substring(1));
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                } else {
                    if (len == 1) {
                        sb.append("0.0").append(s);
                    } else if (len == 2) {
                        sb.append("0.").append(s);
                    } else {
                        sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
                    }
                }
            } else {
                sb.append("0.00");
            }
        } else {
            sb.append("0.00");
        }
        return sb.toString();
    }

    /**
     * 通过金额和费率得到手续费
     * 
     * @param payAmt
     *            分
     * @param rate
     *            万分之
     * @return
     * @author zouwenjun
     * @date 2017年5月23日 上午10:24:03
     */
    public static Integer getRoundFee(Integer payAmt, Integer rate) {
        Integer fee = payAmt * rate;
        BigDecimal b1 = new BigDecimal(Double.valueOf(fee));
        BigDecimal b2 = new BigDecimal(Double.valueOf(10000));
        BigDecimal roundFee = b1.divide(b2, 0, BigDecimal.ROUND_HALF_UP);
        return roundFee.intValue();
    }

    /**
     * 通过交易金额和费率差计算代理商分润，小数点后舍弃
     * 
     * @param payAmt
     * @param subtractRate
     *            代理商之间的费率差
     * @return 最后得到的是代理商的分润
     * @author zouwenjun
     * @date 2017年5月23日 下午1:46:52
     */
    public static BigDecimal getProfit(Integer payAmt, Integer subtractRate) {
        Integer profit = payAmt * subtractRate;
        BigDecimal b1 = new BigDecimal(Double.valueOf(profit));
        BigDecimal b2 = new BigDecimal(Double.valueOf(10000));
        return b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP);
    }

    public static void main(String[] args) {
        // try {
        // logger.info("结果："+changeF2Y("-000a00"));
        // } catch(Exception e){
        // logger.info("----------->>>"+e.getMessage());
        //// return e.getErrorCode();
        // }
        // logger.info("结果："+changeY2F("1.00000000001E10"));

        logger.info(AmountUtils.changeY2F("1.33"));
        try {
            logger.info(AmountUtils.changeF2Y("1322"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // logger.info(Long.parseLong(AmountUtils.changeY2F("1000000000000000")));
        // logger.info(Integer.parseInt(AmountUtils.changeY2F("10000000")));
        // logger.info(Integer.MIN_VALUE);
        // long a = 0;
        // logger.info(a);
        logger.info(getRoundFee(131, 38) + "");
        logger.info(getProfit(131, 2) + "");
    }
}
